﻿using System;
using FubuMVC.Core.Registration;
using FubuMVC.Validation;
using System.Linq;

namespace complex.Services
{
    public class ReturnToPreviousAction
        : IFubuContinuationModelDescriptor
    {
        private readonly BehaviorGraph graph;

        public ReturnToPreviousAction(BehaviorGraph graph)
        {
            this.graph = graph;
        }

        public Type DescribeModelFor(ValidationFailure context)
        {
            var nameOfInputType = context.InputType().FullName ?? "";
            var nameOfDestinationType = nameOfInputType.Replace("Command", "Query");
            var destinationType = Type.GetType(nameOfDestinationType);
            return destinationType ?? graph
                                          .Actions()
                                          .Where(a => a.HandlerType == context.Target.HandlerType)
                                          .Where(a => a.Method.Name == "List")
                                          .Select(a => a.InputType())
                                          .FirstOrDefault();
        }
    }
}